package com.gzist.blog_system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gzist.blog_system.domain.Article;
import com.gzist.blog_system.domain.Statistic;
import com.gzist.blog_system.domain.result.PageBean;
import com.gzist.blog_system.mapper.ArticleMapper;
import com.gzist.blog_system.mapper.StatisticMapper;
import com.gzist.blog_system.service.ArticleService;
import com.gzist.blog_system.service.StatisticService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 *
 */
@Service
@Transactional
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
        implements ArticleService {

    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private StatisticMapper statisticMapper;

    @Override
    public PageBean<Article> queryPage(Integer pageNum, Integer pageSize) {
        // 准备接受数据载体
        PageBean<Article> pb = new PageBean<>();
        Page<Article> page = new Page<>(pageNum, pageSize);
        articleMapper.selectPage(page, null);
        long total = page.getTotal();
        List<Article> records = page.getRecords();
        pb.setTotal(total);
        pb.setItems(records);
        return pb;
    }

    @Override
    public boolean publish(Article article) {
        article.setCreateTime(LocalDateTime.now());
        article.setHit(0L);
        article.setCommentNum(0L);
        int i1 = articleMapper.insert(article);
        int i2 = statisticMapper.insert(article);
        return i1 + i2 > 1;
    }

    @Override
    public List<Article> getHeatArticles() {
        List<Statistic> list = statisticMapper.getStatistic();
        ArrayList<Article> articleList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Article article = articleMapper.selectById(list.get(i).getArticleId());
            article.setHit(list.get(i).getCommentNum());
            articleList.add(article);
            if (i >= 9) {
                break;
            }
        }
        return articleList;
    }
}




